/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.fandi.model;

import com.fandi.dao.CategoryDao;
import com.fandi.dao.impl.CategoryDaoImpl;
import com.fandi.entity.Category;
import com.fandi.listener.CategoryListener;
import java.sql.SQLException;
import java.util.List;

/**
 *
 * @author Fandy
 */
public class CategoryModel extends Category {
    private CategoryListener listener;

    public CategoryListener getListener() {
        return listener;
    }

    public void setListener(CategoryListener listener) {
        this.listener = listener;
    }
    
    @Override
    public void setCode(String code) {
        super.setCode(code);
        fireOnChange();
    }
    
    @Override
    public void setName(String name) {
        super.setName(name);
        fireOnChange();
    }
    
    @Override
    public void setDescription(String description) {
        super.setDescription(description);
        fireOnChange();
    }
    
    public void fireOnChange() {
        if (listener != null) {
            listener.onChange(this);
        }
    }
    
    public void insert() throws SQLException {
        CategoryModel model = new CategoryModel();
        model.setCode(getCode());
        model.setName(getName());
        model.setDescription(getDescription());
        
        CategoryDao dao = new CategoryDaoImpl();
        dao.insert(model);
    }
    
    public void update(String code) throws SQLException {
        CategoryDao dao = new CategoryDaoImpl();
        CategoryModel model = dao.selectBy(code);
        
        model.setId(model.getId());
        model.setCode(getCode());
        model.setName(getName());
        model.setDescription(getDescription());
        
        dao.update(model);
    }
    
    public List<CategoryModel> selectAll() throws SQLException {
        CategoryDao dao = new CategoryDaoImpl();
        List<CategoryModel> list = dao.selectAll();
        
        return list;
    }
    
    public CategoryModel selectById(String code) throws SQLException {
        CategoryDao dao = new CategoryDaoImpl();
        CategoryModel model = dao.selectBy(code);
        
        return model;
    }
    
    public boolean delete(String code) throws SQLException {
        CategoryDao dao = new CategoryDaoImpl();
        
        return dao.delete(code);
    }
    
    public void reset() {
        setCode("");
        setName("");
        setDescription("");
    }
}
